package com.health.system.security.config;


import com.health.system.config.CorsConfig;
import com.health.system.security.auth.BlogAccessDecisionManager;
import com.health.system.security.auth.BlogSecurityMetadataSource;
import com.health.system.security.auth.BlogUserDetailsServiceImpl;
import com.health.system.security.auth.filter.LoginFilter;
import com.health.system.security.handle.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

/**
 * security配置
 *
 */
@Configuration
public class BlogSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${spring.security.login.captcha-enable}")
    private boolean captchaEnable;
    @Value("${spring.security.reject-public-invocations}")
    private boolean rejectPublicInvocations;

    @Autowired
    private BlogUserDetailsServiceImpl userDetailsService;
    @Autowired
    private BlogSecurityMetadataSource metadataSource;
    @Autowired
    private BlogAccessDecisionManager blogAccessDecisionManager;
    @Autowired
    private IgnoreUrlConfig ignoreUrlConfig;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 白名单
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        ignoreUrlConfig.getUrls().forEach(u -> registry.mvcMatchers(u).permitAll());

        // 对所有请求进行授权, 测试方便先将其禁止
        http.authorizeRequests()
                .anyRequest()
                .permitAll()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(blogAccessDecisionManager);
                        object.setSecurityMetadataSource(metadataSource);
                        // 对请求没有进行权限设置, 访问时会抛出错误
                        object.setRejectPublicInvocations(rejectPublicInvocations);
                        return object;
                    }
                });

        // session配置
        http.sessionManagement()
                .maximumSessions(1)
                .sessionRegistry(sessionRegistry());


        // 开启表单认证 && 注销处理
        http.formLogin()
                .and()
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout", "GET"),
                        new AntPathRequestMatcher("/logout", "POST")
                ))
                .logoutSuccessHandler(new BlogLogoutSuccessHandler())
        ;

        // 异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(new BlogAuthenticationEntryPoint())
                .accessDeniedHandler(new BlogAccessDeniedHandler());

        // cors和 csrf处理
        http.cors().configurationSource(new CorsConfig())
                .and().csrf().disable();

        // 替换默认表单过滤器
        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter filter = new LoginFilter();
        filter.setUsernameParameter("username");
        filter.setPasswordParameter("password");
        filter.setCaptchaEnable(captchaEnable);
        filter.setAuthenticationSuccessHandler(new BlogAuthenticationSuccessHandler(sessionRegistry()));
        filter.setAuthenticationFailureHandler(new BlogAuthenticationFailureHandler());
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

}
